#!coding:utf-8

from rest_framework.response import Response

from cvirt.manager.models import Bookmark
from cvirt.manager.serializers import BookmarkSerializer
from cvirt.manager.views import NamedAPIViewMixIn, BaseRetriveAPIView, NonModelBaseAPIView


class ShortcutInfo(NamedAPIViewMixIn, BaseRetriveAPIView):
    model = Bookmark
    serializer_class = BookmarkSerializer

    def delete(self, request, *args, **kwargs):

        _id = kwargs.get('pk')

        bookmark = Bookmark.objects.get(id = _id)
        bookmark.delete()

        dataset = Bookmark.objects.all()
        result = self.paginate(request, dataset, BookmarkSerializer)
        return Response(result)

    def save(self, request, *args, **kwargs):

        name = request.DATA.get("name", "")
        url = request.DATA.get("url", "")
        description = request.DATA.get("description", "")

        Bookmark.objects.create(name=name, url=url, description=description)
        return Response({"result":"ok"})

    def delete_from_thrd(self, request, *args, **kwargs):
        type = request.DATA.get("type")
        ids = request.DATA.get("ids")

        if type and ids:

            for id in ids:
                url = type + "/" + str(id)
                dataset = Bookmark.objects.filter(url__contains=url)
                for bookmark in dataset:
                    bookmark.delete()
        return Response(status=200)

class ShortcutList(NamedAPIViewMixIn, NonModelBaseAPIView):
    serializer_class = BookmarkSerializer

    def _get(self,request,*args,**kwargs):

        dataset = Bookmark.objects.all()
        result = self.paginate(request, dataset, BookmarkSerializer)
        return Response(result)

    def delete_all(self, request, *args, **kwargs):

        ids = request.DATA.get('ids')
        for id in ids:
            Bookmark.objects.get(id=id).delete()

        return self._get(request, args, kwargs)